import { getToken } from "../../../utils/getToken"
import { formateDate } from '../../../utils/formateDate'

Page({
  data: {
    currentDate: Date.now(),
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    // 表单信息
    houseId: '',
    houseInfo: '',
    name: '',
    gender: '2',
    mobile: '',
    visitDate: ''
  },

  onLoad(options) {
    // 获取房屋数据
    this.getHouseList()
  },

  // 获取房屋数据
  getHouseList() {
    wx.request({
      url: 'https://live-api.itheima.net/house',
      method: 'GET',
      header: {
        Authorization: 'Bearer ' + getToken()
      },
      success: (res) => {
        if (res.data.code !== 10000) {
          return wx.showToast({
            title: res.data.message,
          })
        }
        // 设置页面数据
        this.setData({
          houseList: res.data.data
        })
      }
    })
  },


  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  // 选中房屋事件回调函数
  handleHouseSelect(e) {
    console.log(e)
    this.setData({
      houseInfo: e.detail.name,
      houseId: e.detail.id
    })
  },

  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  handleDateConfirm(e) {
    console.log(e)
    this.setData({
      visitDate: formateDate(e.detail),
      dateLayerVisible: false
    })
  },
  handleDateCancel(e) {
    this.setData({ dateLayerVisible: false })
  },

  goPassport() {
    // 表单验证
    if (this.validateVisitData(this.data)) {
      console.log('提交数据吧')
      wx.request({
        url: 'https://live-api.itheima.net/visitor',
        method: 'POST',
        header: {
          Authorization: 'Bearer ' + getToken()
        },
        data: this.data,
        success: (res) => {
          console.log(res)
          // 业务异常判断
          if (res.data.code !== 10000) {
            return wx.showToast({
              title: res.data.message,
            })
          }
          // 设置页面数据
          wx.reLaunch({
            url: `/visitor_pkg/pages/passport/index?id=${res.data.data.id}`,
          })
        }
      })
    }


  },

  // 表单提交验证
  validateVisitData(data) {
    // 房屋信息校验
    if (!data.houseId.trim()) {
      wx.showToast({
        title: '请选择房屋',
      })
      return false
    }

    // 姓名信息校验
    if (!data.name.trim()) {
      wx.showToast({
        title: '请输入访客姓名',
      })
      return false
    }

    // 手机号码校验
    if (!data.mobile.trim()) {
      wx.showToast({
        title: '请输入手机号码',
      })
      return false
    }

    // 手机号正则校验
    const reg = /^[1][3-8][0-9]{9}$/
    if (!reg.test(data.mobile)) {
      wx.showToast({
        title: '手机号码格式错误',
      })
      return false
    }

    // 访问校验
    if (!data.visitDate.trim()) {
      wx.showToast({
        title: '请选择访问',
      })
      return false
    }
    return true
  }
})
